import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';


class DBUtil{

  static Database db;
  static String tableName = 'randomdata';

  //
// 获取数据库中所有的表
  Future<List> getTables() async {
    if (db == null) {
      return Future.value([]);
    }
    List tables = await db
        .rawQuery('SELECT name FROM sqlite_master WHERE type = "table"');
    List<String> targetList = [];
    tables.forEach((item) {
      targetList.add(item['name']);
    });
    return targetList;

  }

// 检查数据库中, 表是否完整, 在部份android中, 会出现表丢失的情况
  Future checkTableIsRight() async {
    List<String> expectTables = ['randomdata','tb_history']; //将项目中使用的表的表名添加集合中

    List<String> tables = await getTables();

    for (int i = 0; i < expectTables.length; i++) {
      if (!tables.contains(expectTables[i])) {
        return false;
      }
    }
    return true;
  }

  Future init() async {
    //Get a location using getDatabasesPath
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'data.db');
    print(path);
    try {
      db = await openDatabase(path);
    } catch (e) {
      print("error $e");
    }

    bool tableIsRight = await this.checkTableIsRight();
    if (!tableIsRight) {
      // 关闭上面打开的db，否则无法执行open
      db.close();
      //表不完整
      // Delete the database
      await deleteDatabase(path);
      db = await openDatabase(path, version: 1,
          onCreate: (Database db, int version) async {
            // When creating the db, create the table
            await db.execute(SqlTable.sql_createTable_randomdata);
            print('db created version is $version');
          }, onOpen: (Database db) async {
            print('new db opened');
          });
    } else {
      print("Opening existing database");
    }
  }

  // 插入
  static Future<int> insertRandomdata(RandomData randomdata) async {
    int value = await db.insert(tableName, randomdata.toMap());
    return value;
  }
  // 根据时间获取
  static Future<RandomData> getRandomdata(DateTime time) async {
    List<Map> maps = await db.query(tableName,
        where: 'time = ?',
        whereArgs: [time]);
    if (maps.length > 0) {
      return RandomData.fromMap(maps.first);
    }
    return null;
  }

  // 获取总数
  static Future<int> getRandomDataCount() async{
    List<Map> maps = await db.query(tableName);
    return maps.length;
  }
  // 获取全部数据
  static Future<List<Map>> getAllRandomData() async{
    List<Map> maps = await db.query(tableName,orderBy: "id desc");
    return maps;
  }
  // 根据id获取
  static Future<RandomData> getRandomData(int id) async{
    List<Map> maps = await db.query(tableName,
        where: 'id = ?',
        whereArgs: [id]);
    if (maps.length > 0) {
      var user = RandomData.fromMap(maps.first);
      return user;
    }else{
      return null;
    }

  }




}

class RandomData{
  int id;
  int time;
  String type;
  String data;
  RandomData(this.time, this.type, this.data);

  Map<String,dynamic> toMap(){
    var map = <String,dynamic>{
      'id':id,
      'time':time,
      'type':type,
      'data':data
    };
    return map;
  }

  RandomData.fromMap(Map<String,dynamic> map){
    id = map['id'];
    time = map['time'];
    type = map['type'];
    data = map['data'];

  }


}
class SqlTable {
  static final String sql_createTable_randomdata = """
    CREATE TABLE randomdata (
    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, 
    time int  NOT NULL, 
    type Text NOT NULL,
    data TEXT NOT NULL);
    """;
}